package com.warodri.gdrivewebviewtest;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.creatingrevolutions.vbukit.lib.FileUtils;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.Toast;

public class MainActivity extends Activity
{
	Context mContext = this;
	WebView webView;
	String authCode = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		init();
	}
	
	private void init()
	{
		webView = (WebView) findViewById(R.id.webView);
		initWebView();
		signGDrive();
	}
	
	private void signGDrive()
	{
		try
		{
			// Another option...
			//webView.loadUrl("http://www.vaskit.com/test/gdriveandroid/index.html");
			
			// Another option...
			//webView.loadUrl("https://drive.google.com");
			
			// I guess the best option...
			webView.loadUrl("https://accounts.google.com/o/oauth2/auth"
					+ "?client_id=545290267853-fc804hsas0mvaj35rh87l9r5dduentio.apps.googleusercontent.com"
					+ "&response_type=code"
					+ "&redirect_uri=http://www.vaskit.com/oauth2callback"
					+ "&scope=openid%20email");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private void initWebView()
	{
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setAllowContentAccess(true);
		webView.getSettings().setAppCacheEnabled(false);
		webView.getSettings().setDomStorageEnabled(true);
		webView.setInitialScale(1);
		webView.getSettings().setPluginState(PluginState.ON);
		webView.setWebChromeClient(new WebChromeClient()
		{});
		webView.getSettings().setAllowFileAccess(true);
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		
		// WebSettings for WebView
		WebSettings webSettings = webView.getSettings();
		
		webSettings.setJavaScriptEnabled(true);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setAllowContentAccess(true);
		webSettings.setLoadsImagesAutomatically(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setSupportZoom(true);
		webSettings.setUseWideViewPort(true);
		webSettings.setDomStorageEnabled(true);
		webSettings.setAppCacheEnabled(true);
		webSettings.setAppCachePath(mContext.getFilesDir().getAbsolutePath()
				+ "/cache");
		webSettings.setDatabaseEnabled(true);
		webSettings.setDatabasePath(mContext.getFilesDir().getAbsolutePath()
				+ "/databases");
		
		webView.setWebViewClient(new WebViewClient()
		{
			boolean authComplete = false;
			
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon)
			{
				super.onPageStarted(view, url, favicon);
			}
			
			@Override
			public void onPageFinished(WebView view, String url)
			{
				super.onPageFinished(view, url);
				
				System.out.println("URL: " + url);

				if (url.contains("googleusercontent.com/") && url.contains("|")) 
				{
					// URL and Filename are separated by a pipe "|"
					String[] arr = url.split("\\|");
					// Hide the WebView
					webView.setVisibility(View.INVISIBLE);
					// Pipe exists?
					if ( arr.length > 1 ) 
					{
						// Get the URL for downloading and the file name
						String downloadUrl = arr[0];
						String fileName = arr[1];
						// Time to download the file
						downloadFile(downloadUrl, fileName);
						return;
					}
				}
				
				if (url.contains("?code=") && authComplete != true)
				{
					Uri uri = Uri.parse(url);
					authCode = uri.getQueryParameter("code");
					Log.i("", "CODE : " + authCode);
					authComplete = true;
					// This should be changed to vbukit.biz or similar...
					webView.loadUrl("http://www.vaskit.com/test/gdriveandroid/index.html");
				}
				else if (url.contains("error=access_denied"))
				{
					showToast("Access Denied.");
				}
			}
		});
		
	}
	
	private void downloadFile(final String url, final String fileName)
	{
		System.out.println("Downloading: " + url);
		
		final ProgressDialog progress = new ProgressDialog(mContext);
		progress.setMessage("Downloading file. Please wait...");
		progress.show();
		
		Thread t = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				try {
					// Get file's bytes
					byte[] data = getUrlContent(url);
					// Define path for downloading the file
					String path = Environment.getExternalStorageDirectory() + "/" + fileName;
					// Write content to disk
					FileUtils.writeFileToSDCard(path, data, true);
					// Remove dialog
					progress.dismiss();
					// Inform user
					showToast("File Downloaded.");
				}
				catch ( Exception e ) 
				{
					e.printStackTrace();
					// Inform user
					showToast("Error occurred downloading file.");
				}
			}
		});
		t.start();
	}
	
	

	/*
	 * Just is a file-downloader...
	 */
	public byte[] getUrlContent(String urlstring) throws IOException
	{
	    byte[] imageRaw = null;
	    URL url = new URL(urlstring);
	    
	    HttpURLConnection urlConnection = (HttpURLConnection) url
	            .openConnection();
	    urlConnection.setUseCaches(false);
	    urlConnection.connect();
	    if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
	    {
	        try
	        {
	            InputStream in = new BufferedInputStream(
	                    urlConnection.getInputStream());
	            ByteArrayOutputStream out = new ByteArrayOutputStream();
	            int c;
	            while ((c = in.read()) != -1)
	            {
	                out.write(c);
	            }
	            out.flush();

	            imageRaw = out.toByteArray();

	            urlConnection.disconnect();
	            in.close();
	            out.close();
	        } 
	        catch (IOException e)
	        {
	            e.printStackTrace();
	        }
	        return imageRaw;
	        // Uncomment if you want to download as Base64
	        // return Base64.encodeToString(imageRaw, Base64.DEFAULT);
	    }
	    return null;
	}
	
	
	/*
	 * In case you want to change current WebView's user agent.
	 */
	private void setUserAgent(String newUserAgent)
	{
		webView.getSettings().setUserAgentString(newUserAgent);
	}
	
	/*
	 * Show Toast in view thread
	 */
	private void showToast(final String message)
	{
		runOnUiThread(new Runnable()
		{
			@Override
			public void run()
			{
				Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
				
			}
		});
	}
}
